import { ProForm, QueryFilter } from '@/components/Pro';
import { parseArray } from '@/pages/Statistics/Battery/utils';
import { TreeNode } from '@/pages/Statistics/PowerGeneration/help';
import { getDeviceCascader } from '@/utils/formatterTree';
import { useIntl, useModel } from '@umijs/max';
import { Button, DatePicker, Space, TreeSelect } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';

type IProps = {
  dateType: string;
  handleSubmit: (data: any) => void;
};
const ChartForm: React.FC<IProps> = (props) => {
  const intl = useIntl();
  const [date, setDate] = useState<Dayjs>(dayjs());
  const { dateType, handleSubmit } = props;
  const treeData = useRef(null);
  const [areaId, setAreaId] = useState<string[] | number[] | null>(null);
  const [dimensions, setDimensions] = useState();
  const { initialState } = useModel('@@initialState');
  const selectedType = useRef(null);

  /**
   * 获得禁用列表
   * @param Nodes
   */
  const setDisabled = (Nodes: TreeNode[]): TreeNode[] => {
    return Nodes.map((node) => {
      const newNode: TreeNode = {
        ...node,
        disabled: selectedType.current === null ? false : node.nodeType !== selectedType.current,
      };
      if (newNode.subDevices) {
        newNode.subDevices = setDisabled(newNode.subDevices);
      }
      return newNode;
    });
  };
  useEffect(() => {
    if (initialState?.isArea) {
      getDeviceCascader(false, 2).then((res) => {
        setDimensions(res[0].uniqueId);
        selectedType.current = 'ROOT';
        treeData.current = setDisabled([res[0]]);
      });
    }
  }, []);
  return (
    <div>
      <QueryFilter submitter={false} style={{ paddingBottom: 0 }}>
        <ProForm.Item label={intl.formatMessage({ id: 'statistics.income.select' })}>
          <DatePicker
            allowClear={false}
            value={date}
            onChange={(date) => {
              setDate(date);
            }}
            defaultValue={dayjs()}
            picker={dateType}
            disabledDate={(current) => {
              return current && current > moment().endOf('day');
            }}
            style={{ width: '100%' }}
          ></DatePicker>
        </ProForm.Item>
        {initialState?.isArea && (
          <ProForm.Item label={intl.formatMessage({ id: 'hisCurve.dimensions' })}>
            <TreeSelect
              style={{ width: '200px' }}
              value={dimensions}
              treeData={treeData?.current}
              multiple={true}
              maxTagCount={'responsive'}
              maxCount={100}
              fieldNames={{
                label: 'deviceName',
                value: 'uniqueId',
                children: 'subDevices',
              }}
              onSelect={(...args) => {
                let selectOptions = args[1];
                if (selectedType.current === null && selectOptions?.nodeType) {
                  selectedType.current = selectOptions?.nodeType;
                }
                treeData.current = setDisabled([treeData?.current[0]]);
              }}
              onChange={(...args) => {
                setDimensions(args[0]);
                let selectedOptions = args[1];
                if (!selectedOptions.length) {
                  //清除后不再做相应限制
                  selectedType.current = null;
                  treeData.current = setDisabled([treeData?.current[0]]);
                }
                let hasAreaNode: boolean = false;
                const ans = parseArray(args[0]);
                if (ans.nodeType.length) {
                  hasAreaNode = ans.nodeType.some((item: string) => {
                    return item === 'AREA';
                  });
                }
                if (hasAreaNode) {
                  setAreaId(ans.id);
                  handleSubmit({
                    date: date,
                    areaIdList: ans.id,
                  });
                } else {
                  handleSubmit({
                    date: date,
                    areaIdList: null,
                  });
                }
              }}
            ></TreeSelect>
          </ProForm.Item>
        )}
        <ProForm.Item>
          <Space>
            <Button
              type={'primary'}
              onClick={() => {
                handleSubmit({
                  date: date,
                  areaIdList: areaId,
                });
              }}
            >
              {intl.formatMessage({ id: 'global.search' })}
            </Button>
            <Button
              onClick={() => {
                if (initialState?.isArea) {
                  selectedType.current = 'ROOT';
                  treeData.current = setDisabled([treeData?.current?.[0]]);
                  setDimensions(treeData?.current?.[0].uniqueId);
                  setAreaId(null);
                }
                setDate(dayjs());
                handleSubmit({
                  date: dayjs(),
                  areaIdList: null,
                });
              }}
            >
              {intl.formatMessage({ id: 'global.reset' })}
            </Button>
          </Space>
        </ProForm.Item>
      </QueryFilter>
    </div>
  );
};

export default ChartForm;
